<style lang="scss">
.questionnaire {
  display: flex;
  flex-direction: column;
  background-repeat: no-repeat;
  background-size: 100%;
  min-height: 100%;
  height: 100%;
  // width: 100%;
  width: 7.5rem;
  position: absolute;
  left: 0;
  right: 0;
  margin: auto;
  overflow: hidden;

  .cover-image {
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;

    img {
      width: 100%;
    }
  }
}
.question-title {
  width: 100%;
  padding: 60px 0 0;
  height: 60px;
  font-size: 38px;
  color: #fff;
  text-align: center;
}
.question-subtitle {
  width: calc(100% - 80px);
  padding: 40px;
  height: 80px;
  font-size: 32px;
  color: #fff;
  text-align: center;
}

.question-content {
  width: calc(100% - 40px);
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  margin: 20px 20px 0;
  height: calc(100% - 300px);
  min-height: calc(100% - 300px);
  background: #fff;
  color: #333;
  overflow: scroll;
  -webkit-overflow-scrolling: touch;
}
.question-content > div {
  transition: opacity 0.3s ease;
}
.question-content > .disabled {
  user-select: none;
  pointer-events: none;
  opacity: 0.2;
}
.question-content::-webkit-scrollbar {
  height: 0;
}

.question-commit {
  padding: 100px 0;
  width: 100%;
  text-align: center;
  position: relative;

  .commit-btn {
    width: 300px;
    height: 80px;
    line-height: 80px;
    background: #353a51;
    color: #fff;
    /* background: #695CFF; */
    border-radius: 40px;
    text-align: center;
    vertical-align: middle;
    display: inline-block;
  }
}

.mint-msgbox {
  position: absolute;
  top: 50vh;
  left: 50%;
  -webkit-transform: translate3d(-50%, -50%, 0);
  transform: translate3d(-50%, -50%, 0);
  background-color: #fff;
  width: 637.5px;
  border-radius: 3px;
  font-size: 32px;
  -webkit-user-select: none;
  overflow: hidden;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}
.mint-msgbox-header {
  padding: 15px 0 0;
}
.mint-msgbox-content {
  padding: 30px 30px 35px;
  border-bottom: 1px solid #ddd;
  min-height: 36px;
  position: relative;
}
.mint-msgbox-input {
  padding-top: 15px;
}
.mint-msgbox-input input {
  border: 1px solid #dedede;
  border-radius: 5px;
  padding: 4px 5px;
  width: 100%;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
}
.mint-msgbox-input input.invalid {
  border-color: #ff4949;
}
.mint-msgbox-input input.invalid:focus {
  border-color: #ff4949;
}
.mint-msgbox-errormsg {
  color: red;
  font-size: 12px;
  min-height: 18px;
  margin-top: 2px;
}
.mint-msgbox-title {
  text-align: center;
  padding-left: 0;
  margin-bottom: 0;
  font-size: 24px;
  font-weight: 700;
  color: #333;
}
.mint-msgbox-wrapper {
  width: 100%;
  // height: 100%;
}
.mint-msgbox-message {
  color: #999;
  margin: 0;
  text-align: center;
  line-height: 36px;
}
.mint-msgbox-btns {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  height: 80px;
  line-height: 80px;
}
.mint-msgbox-btn {
  line-height: 45px;
  font-size: 32px;
  display: block;
  background-color: #fff;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  margin: 0;
  border: 0;
}
.mint-msgbox-btn:focus {
  outline: none;
}
.mint-msgbox-btn:active {
  background-color: #fff;
}
.mint-msgbox-cancel {
  width: 50%;
  border-right: 1px solid #ddd;
}
.mint-msgbox-cancel:active {
  color: #000;
}
.mint-msgbox-confirm {
  color: #26a2ff;
  width: 50%;
}
.mint-msgbox-confirm:active {
  color: #26a2ff;
}
.msgbox-bounce-enter {
  opacity: 0;
  -webkit-transform: translate3d(-50%, -50%, 0) scale(0.7);
  transform: translate3d(-50%, -50%, 0) scale(0.7);
}
.msgbox-bounce-leave-active {
  opacity: 0;
  -webkit-transform: translate3d(-50%, -50%, 0) scale(0.9);
  transform: translate3d(-50%, -50%, 0) scale(0.9);
}

.v-modal-enter {
  -webkit-animation: v-modal-in 0.2s ease;
  animation: v-modal-in 0.2s ease;
}
.v-modal-leave {
  -webkit-animation: v-modal-out 0.2s ease forwards;
  animation: v-modal-out 0.2s ease forwards;
}
@-webkit-keyframes v-modal-in {
  0% {
    opacity: 0;
  }
  100% {
  }
}
@keyframes v-modal-in {
  0% {
    opacity: 0;
  }
  100% {
  }
}
@-webkit-keyframes v-modal-out {
  0% {
  }
  100% {
    opacity: 0;
  }
}
@keyframes v-modal-out {
  0% {
  }
  100% {
    opacity: 0;
  }
}
.v-modal {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0.5;
  background: #000;
}
.question-result {
  z-index: 100;
  background: transparent;
  background-color: rgba(0, 0, 0, 0.9);
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}

.question-result > .result-panel {
  width: 100%;
  position: absolute;
  left: 0;
  top: 25%;
  text-align: center;
}

.question-result > .result-panel > img {
  width: 600px;
  padding: 20px;
}

.question-result > .result-panel > .result-title {
  padding: 20px 0 0;
  font-size: 38px;
  font-weight: bold;
  color: #333;
}
.question-result > .result-panel > .result-content {
  padding: 20px 0 0;
  font-size: 32px;
  color: #fff;
}
.question-result > .result-panel > .result-btn {
  font-size: 36px;
  color: #108ee9;
  padding: 60px 0;
  border-top: 1rpx solid #f6f6f6;
}
</style>
<template>
  <div class="questionnaire"
       :style="{backgroundImage:'url(' + forground + ')'}"
       v-if="!begin"
       @click="onShowClick">
    <div class='cover-image'>
      <img :src="forground"></img>
    </div>
  </div>
  <div class="questionnaire"
       :style="{backgroundImage:'url(' + background + ')'}"
       v-else>
    <div class="question-title">{{title}}</div>
    <div class="question-subtitle">{{description}}</div>
    <div class="question-content">

      <template v-for="(item, index) in question">
        <Question :index="index + 1"
                  :title="item.title"
                  :class="{disabled: !(enabledQid[item.sort] && enabledQid[item.sort].enabled)}"
                  v-model="answer[item.id]"
                  @input="val => handleAnswer(item, val)"
                  v-if="item.type == '1'" />
        <SingleSelect :index="index + 1"
                      :title="item.title"
                      :options="item.selection"
                      :class="{disabled: !(enabledQid[item.sort] && enabledQid[item.sort].enabled)}"
                      v-model="answer[item.id]"
                      @input="(val, next) => handleAnswer(item, val, next)"
                      v-if="item.type == '2'" />
        <MultiSelect :index="index + 1"
                     :title="item.title"
                     :options="item.selection"
                     :max="item.selection_max"
                     :class="{disabled: !(enabledQid[item.sort] && enabledQid[item.sort].enabled)}"
                     v-model="answer[item.id]"
                     @input="val => handleAnswer(item, val)"
                     v-if="item.type == '3'" />
        <Dropdown :index="index + 1"
                  :title="item.title"
                  :options="item.selection"
                  :class="{disabled: !(enabledQid[item.sort] && enabledQid[item.sort].enabled)}"
                  v-model="answer[item.id]"
                  @input="(val, next) => handleAnswer(item, val, next)"
                  v-if="item.type == '4'" />
      </template>

      <div class='question-commit'>
        <div class='commit-btn'
             :style="{background: color}"
             @click='onCommitClick'>提 交</div>
      </div>
    </div>

    <div class='question-result'
         v-if="show">
      <div class='result-panel'>
        <img src="../assets/success.png"></img>
        <div class='result-content'>感谢您的回答及宝贵时间，</div>
        <div class='result-content'>我们将认真对待您的建议！</div>
        <div class='result-btn'
             @click='onFinishClick'>确 定</div>
      </div>
    </div>
  </div>

</template>

<script>
// @ is an alias to /src
import Question from "@/components/Question.vue";
import SingleSelect from "@/components/SingleSelect.vue";
import MultiSelect from "@/components/MultiSelect.vue";
import Dropdown from "@/components/Dropdown.vue";
import { MessageBox } from "mint-ui";
import configWxShare from '../helpers/configWxShare'

export default {
  name: "questionnaire",
  components: {
    Question,
    SingleSelect,
    MultiSelect,
    Dropdown,
  },
  data() {
    return {
      pid: 0,
      qid: 0,
      begin: false,
      show: false,
      title: "",
      description: "",
      color: "",
      forground: "",
      background: "",
      running: "0",
      question: [],
      answer: [],
      enabledQid: {},
    };
  },
  computed: {
    questionMap() {
      return this.question.reduce((res, item) => ({...res, [item.sort]: item}), {})
    }
  },
  created() {
    this.pid = this.$route.query.pid;
    this.qid = this.$route.query.qid;
    console.log(this.pid);

    var self = this;
    $.ajax({
      url:
        "https://evp.51job.com/51job/api/51miniadmin/h5.php?projectid=" +
        this.pid +
        "&action=questionnaire_config&qid=" +
        this.qid,
      type: "POST",
      dataType: "json",
      success: function (data) {
        // console.log(data);
        if (data.data != null) {
          self.color = data.data.bg_color;
          self.forground =
            "https://evp.51job.com/51job/api/51miniadmin/" + data.data.hp_pic;
          self.background =
            "https://evp.51job.com/51job/api/51miniadmin/" + data.data.bg_pic;
          self.title = data.questionnaire.title;
          self.description = data.questionnaire.memo;
          self.running = data.questionnaire.is_running;
          // 配置微信转发
          configWxShare(data.data.wx_title, data.data.wx_desc, data.data.wx_logo)
        }
      },
    });
    $.ajax({
      url:
        "https://evp.51job.com/51job/api/51miniadmin/h5.php?projectid=" +
        this.pid +
        "&action=questionnaire_list&qid=" +
        this.qid,
      type: "POST",
      dataType: "json",
      success: function (data) {
        // console.log(data);

        if (data.data != null) {
          self.question = data.data;
          var array = {};
          for (var i = 0; i < data.data.length; i++) {
            array[data.data[i].id] = "";
          }
          self.answer = array;

          // 初始化可答题map
          self.enabledQid[self.question[0].sort] = {
            enabled: true,
            next: self.question[0].goto === '0' ? 2 : self.question[0].goto,
            id: self.question[0].id
          };
        }
      },
    });
  },
  mounted() {
    this.$("body").on("blur", "input", () => {
      window.scroll(0, 0);
      $(document).scrollTop(0);
    });
  },
  methods: {
    onShowClick: function (e) {
      this.begin = true;
    },
    isFinished() {
      const _isFinished = item => {
        if(Number(item.next) > Object.keys(this.answer).length) return true
        if (!item) return false
        return _isFinished(this.enabledQid[item.next])
      }
      return _isFinished(this.enabledQid['1'])
    },
    onCommitClick: function (e) {
      // 判断是否全部填写
      if(!this.isFinished()) {
        MessageBox.alert("请填写完整信息", "注意");
        return;
      }
     
      var self = this;
      try {
        MessageBox.confirm("请确认提交信息是否正确!")
          .then(function (r) {
            self.commitAnswer();
          })
          .catch(function (err) {
            //
            console.log(err)
          });
      } catch (e) {
        console.log(e);
      }
    },
    nextKey(from, to) {
      return to === "0" ? parseInt(from) + 1 : parseInt(to);
    },
    enableList(key) {
      // 递归开启
      let callCnt = 0;
      const _enable = (key, map) => {
        if (map[key]) {
          map[key].enabled = true;
          // 环检测
          if(callCnt <= Object.keys(map).length) {
            callCnt ++;
            if (map[key].val) _enable(map[key].next, map);
          } else {
            MessageBox.alert("问卷出现环路径问题，请保证逻辑顺利", "注意");
          }
          
        }
      };
      _enable(key, this.enabledQid);
    },
    disableList(key) {
      // 递归禁用
      let callCnt = 0;
      const _disable = (key, map) => {
        if (map[key]) {
          map[key].enabled = false;
          // 环检测
          if(callCnt <= Object.keys(map).length) {
            callCnt ++;
            _disable(map[key].next, map);
          } else {
            MessageBox.alert("问卷出现环路径问题，请保证逻辑顺利", "注意");
          }
        }
      };
      _disable(key, this.enabledQid);
    },
    handleAnswer(item, val, _next) {
      // 记录数值修改
      this.enabledQid[item.sort].val = val;

      // next发生改变则关闭 lastNext 子链, 并赋值next
      const lastNext = this.enabledQid[item.sort].next;
      if(_next && lastNext && lastNext !== _next) {
        this.disableList(lastNext);
        this.enabledQid[item.sort].next = this.nextKey(item.sort, _next)
      }
      // 计算next
      const next = this.nextKey(item.sort, _next || item.goto);

      if (val) {
        // 判断 next 是否为自身
        if (String(next) === item.sort) return;
        // 开启 next 可编辑状态
        this.enabledQid[next] = this.enabledQid[next] || {
          id: this.questionMap[next] && this.questionMap[next].id,
          enabled: true,
          next: this.nextKey(next, this.questionMap[next] ? this.questionMap[next].goto : '0'),
          val: '',
        };
        this.enableList(next);
      } else {
        // 关闭可编辑状态
        this.disableList(next);
      }
    },
    getAnswer() {
      let answer = {}
      let key = '1'
      while(this.enabledQid[key]) {
        console.log(123)
        const question = this.enabledQid[key]
        if(question.id && question.val) {
          answer[question.id] = question.val
        }
        key = question.next
      }
      return answer
    },
    commitAnswer: function () {
      var data = JSON.stringify(this.getAnswer());
      
      var self = this;
      $.ajax({
        url:
          "https://evp.51job.com/51job/api/51miniadmin/h5.php?projectid=" +
          this.pid +
          "&action=questionnaire_user_add&qid=" +
          this.qid,
        type: "POST",
        data: { selection_all: data },
        dataType: "json",
        success: function (data) {
          console.log(data);
          if (data.code == 1) {
            self.show = true;
          }
        },
      });
    },
    onFinishClick: function (e) {
      this.answer = {};
      this.show = false;
      this.begin = false;
    },
  },
};
</script>
